<?php

namespace App\Http\Controllers\Prize;

use App\Entities\DrawRecord;
use App\Entities\PrizeLogistics;
use App\Entities\LogisticsCompany;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;

class ApiController
{
    public function doExchange(Request $request)
    {
        $factory = app('validator');
        $input = $request->json()->all();

        $validator = $factory->make($input, [
            'id' => 'required|uuid|exists:activity_records',
            'fileds' => 'array',
        ]);

        if ($validator->fails()) {
            return response()->failed($validator->errors()->first());
        }

        $success = DrawRecord::query()
            ->where('id', $input['id'])
            ->update([
                'is_exchange' => 1,
                'is_confirm' => 1,
                'extends' => json_encode(Arr::get($input, 'fileds', [])),
            ]);

        if ($success) {
            return response()->success();
        }

        return response()->filed('保存失败');
    }

    public function getLogisticsCompanies()
    {
        $cache = app('cache');

        $companies = $cache->remember('logistics:companies', 10, function () {
            return LogisticsCompany::query()
                ->get(['id', 'name', 'bukrs', 'hotline']);
        });

        return response()->success($companies);
    }

    public function setLogistics(Request $request)
    {
        $factory = app('validator');
        $input = $request->json()->all();

        $validator = $factory->make($input, [
            'record_id' => 'required|uuid',
            'company_id' => 'required|uuid',
            'order_number' => 'required|max:255',
        ]);

        if ($validator->fails()) {
            return response()->failed($validator->errors()->first());
        }

        $database = app('db');

        $success = $database->transaction(function () use ($input) {
            DrawRecord::query()
                ->where('id', $input['record_id'])
                ->update(['is_exchange' => 1]);

            $logistics = new PrizeLogistics();
            $logistics->fill($input);

            return $logistics->save();
        });

        if ($success) {
            return response()->success();
        }

        return response()->failed('添加失败');
    }
}
